package com.xs.ahoi.hcxs.ui.activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.text.SpannableStringBuilder;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.AbsListView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import com.xs.ahoi.hcxs.R;
import com.xs.ahoi.hcxs.model.vo.SearchDataVo;
import com.xs.ahoi.hcxs.service.BookFactory;
import com.xs.ahoi.hcxs.utils.Constants;
import com.xs.ahoi.hcxs.utils.MapUtil;
import com.xs.ahoi.hcxs.utils.ObjectUtils;
import com.xs.ahoi.hcxs.utils.StringUtils;
import com.xs.ahoi.hcxs.utils.ThreadPoolFactory;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.OnItemClick;

/**
 * 全文搜索
 */
public class BookSearchActivity extends BaseActivity {

    @BindView(R.id.searchStr)
    public EditText searchStr;
    @BindView(R.id.searchCount)
    public TextView searchCount;
    @BindView(R.id.searchResult)
    public ListView searchResult;
    @BindView(R.id.ivLoading)
    public ImageView ivLoading;

    // 搜索文字
    private String searchText;
    private String searchCountTemp = "当前已找到xx个结果";
    private String fontStyleStart = "<font color=\"#ff0000\">";
    private String fontStyleEnd = "</font>";
    // 搜索结果
    private List<Map<String, Object>> datas = new ArrayList<>();
    private BookFactory bookFactory = BookFactory.getInstance();
    private BookSearchAdapter adapter;
    // loading动画
    private AnimationDrawable loading;

    // 异步发消息
    private List<SearchDataVo> searchDataVoList;
    private Handler mHandler;
    private Message message;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_book_search);
        ButterKnife.bind(this);
        init();
    }

    @SuppressLint("HandlerLeak")
    private void init() {

        // loading动画
        loading = (AnimationDrawable) ivLoading.getBackground();
        loading.start();

        // 绑定adapter
        adapter = new BookSearchAdapter(this, datas, R.layout.listview_item_search, new String[]{"text", "percent"}, new int[]{R.id.tvText, R.id.tvPercent});
        searchResult.setAdapter(adapter);

        // 添加搜索框监听
        searchStr.setOnEditorActionListener(new TextView.OnEditorActionListener() {

            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEND
                        || actionId == EditorInfo.IME_ACTION_NEXT
                        || actionId == EditorInfo.IME_ACTION_GO
                        || actionId == EditorInfo.IME_ACTION_SEARCH
                        || actionId == EditorInfo.IME_ACTION_DONE
                        || (event != null && KeyEvent.KEYCODE_ENTER == event.getKeyCode() && KeyEvent.ACTION_DOWN == event.getAction())) {
                    searchText = searchStr.getText().toString();
                    if (searchText.length() > 0) {
                        reSearch();
                    }
                }
                return true;
            }
        });

        // 添加滚动监听
        searchResult.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                // 滚动到最后一个时，继续搜索
                if (searchText != null && view.getLastVisiblePosition() == totalItemCount - 1 && bookFactory.canSearchContinue()) {
                    search();
                }
            }
        });

        mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what) {
                    case 1:
                        searchDataVoList = bookFactory.startSearch(searchText);
                        bindListView(searchDataVoList);
                        break;
                    case 2:
                        searchDataVoList = bookFactory.reStartSearch(searchText);
                        bindListView(searchDataVoList);
                        break;
                }
            }
        };

        // 是否默认执行搜索
        defaultSearch();
    }

    private void defaultSearch() {
        String paramText = getIntent().getStringExtra("searchText");
        if (StringUtils.isNotEmpty(paramText)) {
            searchText = paramText;
            searchStr.setText(paramText);
            reSearch();
        }
    }

    private void search() {
        ivLoading.setVisibility(View.VISIBLE);
        ThreadPoolFactory.getInstance().execute(() -> {
            Message message = new Message();
            message.what = 1;
            mHandler.sendMessage(message);
        });
    }

    private void reSearch() {
        ivLoading.setVisibility(View.VISIBLE);
        ThreadPoolFactory.getInstance().execute(() -> {
            Message message = new Message();
            message.what = 2;
            mHandler.sendMessage(message);
        });
    }

    private void bindListView(List<SearchDataVo> list) {
        datas.clear();
        for (SearchDataVo vo : list) {
            datas.add(MapUtil.build()
                    .put("text", vo.getText())
                    .put("percent", vo.getPercent())
                    .put("index", vo.getIndex())
                    .put("matchIndex", vo.getMatchIndex())
                    .put("searchText", vo.getSearchText())
                    .over());
        }
        adapter.notifyDataSetChanged();
        searchCount.setText(searchCountTemp.replace("xx", String.valueOf(datas.size())));

        new Handler().postDelayed(new Runnable() {
            public void run() {
                ivLoading.setVisibility(View.INVISIBLE);
            }
        }, 200);
    }

    @OnClick({R.id.arrowLeft})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.arrowLeft:
                super.onBackPressed();
                break;
            default:
                break;
        }
    }

    @OnItemClick({R.id.searchResult})
    public void onItemClick(int position) {
        // 跳转到内容页面的指定下标位置
        int index = ObjectUtils.toInteger(datas.get(position).get("index"));
        Bundle bundle = new Bundle();
        bundle.putInt(Constants.POSITION, index);
        setResult(Constants.RESULT_CODE_CATALOG_OR_SEARCH, new Intent().putExtras(bundle));
        finish();
    }


    // 自定义SimpleAdapter
    private class BookSearchAdapter extends SimpleAdapter {

        private BookSearchAdapter(Context context, List<? extends Map<String, Object>> datas, int resource, String[] from, int[] to) {
            super(context, datas, resource, from, to);
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View view = super.getView(position, convertView, parent);
            Map<String, Object> data = getItem(position);

            // 设置内容，匹配文字红色
            TextView tvText = view.findViewById(R.id.tvText);
            String showText = ObjectUtils.toString(data.get("text"));
            String searchText = ObjectUtils.toString(data.get("searchText"));
            int matchIndex = ObjectUtils.toInteger(data.get("matchIndex"));
            SpannableStringBuilder builder = new SpannableStringBuilder(showText);
            builder.insert(matchIndex, fontStyleStart).insert(matchIndex + fontStyleStart.length() + searchText.length(), fontStyleEnd);
            tvText.setText(Html.fromHtml(builder.toString()));

            // 设置进度
            TextView tvPercent = view.findViewById(R.id.tvPercent);
            tvPercent.setText(ObjectUtils.toString(data.get("percent")));

            return view;
        }

        @Override
        public Map<String, Object> getItem(int position) {
            return datas.get(position);
        }
    }

}
